const Token = require('../../utils/token');
const request = require('../../utils/request');
const WXChat = require('../../config/WXchat');
class UserController {
    /**
     * 通过微信接口获取用户信息
     * @api {POST}        /user/login          通过微信接口获取用户信息
     * @apiName           /user/login
     * @apiGroup          User
     * @apiVersion 0.1.0
     * @apiParam          {String}          code         code
     * @apiParam          {String}          avatarUrl    avatarUrl
     * @apiParam          {String}          nickName     nickName
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": ""
      }
     */
    async login(ctx) {
        let {
            db,
            request: {
                body: { code, avatarUrl, nickName }
            }
        } = ctx;

        if (!code) {
            ctx.errors('code不能为空！');
            return;
        }

        if (!avatarUrl) {
            ctx.errors('头像不能为空！');
            return;
        }

        if (!nickName) {
            ctx.errors('名称不能为空！');
            return;
        }

        // 获取url
        const url = await WXChat.Wx(code);

        const res = await request.get(url);

        if (res.errcode) {
            ctx.errors(res.errmsg);
            return;
        }
        // 插入数据
        try {
            let data;
            data = await db.User.findOne({ where: { openId: res.openid } });
            if (data) {
                data.sessionKey = res.session_key;
                data.avatarUrl = avatarUrl;
                data.nickName = nickName;
                data.save();
            } else {
                let condition = {
                    openId: res.openid,
                    sessionKey: res.session_key,
                    avatarUrl: avatarUrl,
                    nickName: nickName
                };
                data = await db.User.create(condition);
            }
            let token = Token.createToken(
                data,
                data.id,
                '8800',
                'hours',
                'app'
            );
            ctx.success({ token: token });
        } catch (e) {
            // rollback transaction
            console.log(e);
            ctx.errors('获取失败，请稍后再试');
            return;
        }
    }
}

module.exports = new UserController();
